package com.chinacoal.hr.levelimpl.client;

import com.chinacoal.hr.levelapi.entity.AttendanceInfoTemp;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import sun.net.www.protocol.http.HttpURLConnection;


import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author: YunTao.Li
 * @create: 2019-12-21 21:16
 * @description: 获得考勤接口的考勤相关数据
 **/
@Component
public class AttendanceWebClient {
//    private static final String WSDL_ATTENDANCE = "http://117.122.198.228/CICloud/services/BusWebService?wsdl";
    private static final String WSDL_ATTENDANCE = "http://172.20.0.235:8081/CICloud/services/BusWebService?wsdl";

    public static void main(String[] args) {
        try {
            String startDateStr = "2020-05-17";
            String endDateStr = "20190808";

            new AttendanceWebClient().attendanceDetailSyncLoader(startDateStr, endDateStr);
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

    /**
     * 考勤明细数据同步器
     *
     * @param beginDate :
     * @param endDate   :
     * @return : void
     * @author : YunTao.Li
     * @date : 2019/12/21 2019/12/21
     */
    public List<AttendanceInfoTemp> attendanceDetailSyncLoader(String beginDate, String endDate) throws Throwable {
        try {

            // step1 : 调用接口，获得考勤明细xml
            String methodName = "getAttendMsg";
            StringBuilder attendanceDetailResXML = this.getAttendanceDetailResXML(beginDate, endDate, methodName);
            Document doc = DocumentHelper.parseText(attendanceDetailResXML.toString()); // 将字符串转为XML

            // step2 : 遍历各项节点
            Element rootElt = doc.getRootElement(); // 获取根节点
            Element attendDetailElement = rootElt.element("attendDetail");
            Element dataInfoElement = attendDetailElement.element("dataInfo");

            // step3 : 遍历baseinfo节点，每个baseinfo代表某人一天的数据
            List<AttendanceInfoTemp> attendanceInfoTempList = new ArrayList();
            Iterator iter = dataInfoElement.elementIterator("baseInfo"); // 获取根节点下的子节点head
            while (iter.hasNext()) {
                AttendanceInfoTemp attendanceInfoTemp = new AttendanceInfoTemp();
                Element baseInfoElement = (Element) iter.next();
                Iterator elementIterator = baseInfoElement.elementIterator("element");

                // step4 : 遍历各项属性
                while (elementIterator.hasNext()) {
                    Element element = (Element) elementIterator.next();
                    String attName = element.attributeValue("name");
                    String attValue = element.attributeValue("value");
                    String attId = element.attributeValue("id");

                    // 跳过空值的属性
                    if (StringUtils.isBlank(attValue)) {
                        continue;
                    }

                    try {
                        if (("signoutaddr").equals(attId)) { //签退地点
                            attendanceInfoTemp.setSignOutAddr(attValue);
                        } else if (("signin").equals(attId)) { //签到时间
                            attendanceInfoTemp.setSignUp(Integer.parseInt(attValue));
                        } else if (("username").equals(attId)) { //员工姓名
                            attendanceInfoTemp.setEmpName(attValue);
                        } else if (("signoutstatus").equals(attId)) { //签退状态
                            attendanceInfoTemp.setSignOutStatus(attValue);
                        } else if (("signout").equals(attId)) { //签退时间
                            attendanceInfoTemp.setSignOut(Integer.parseInt(attValue));
                        } else if (("usercode").equals(attId)) { //员工编码
                            attendanceInfoTemp.setEmpCode(attValue);
                        } else if (("signupaddr").equals(attId)) { //签到地点
                            attendanceInfoTemp.setSignUpAddr(attValue);
                        } else if (("signininfo").equals(attId)) { //签到备注
                            attendanceInfoTemp.setSignUpInfo(attValue);
                        } else if (("signinstatus").equals(attId)) { //签到状态
                            attendanceInfoTemp.setSignUpStatus(attValue);
                        } else if (("groupname").equals(attId)) { //组织名称
                            attendanceInfoTemp.setOrgName(attValue);
                        } else if (("attenddate").equals(attId)) { //考勤日期
                            Date attendDate = new SimpleDateFormat("yyyyMMdd").parse(attValue);
                            String weekStr = new SimpleDateFormat("EEEE").format(attendDate);
                            attendanceInfoTemp.setAttendDate(attendDate);
                            attendanceInfoTemp.setWeekDay(weekStr);
                        } else if (("deptname").equals(attId)) { //部门名称
                            attendanceInfoTemp.setDeptName(attValue);
                        } else if (("signoutinfo").equals(attId)) { //签退备注
                            attendanceInfoTemp.setSignOutInfo(attValue);
                        }
                    } catch (Exception e) {
                        System.out.println("attName:" + attName + " attValue:" + attValue + " attId:" + attId);
                        e.printStackTrace();
                    }
                }
//                System.out.println(attendanceInfoTemp.getAttendDate());
                attendanceInfoTempList.add(attendanceInfoTemp);
            }

//            System.out.println("list size:" + attendanceInfoTempList.size());
            return attendanceInfoTempList;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 调用接口，获得考勤明细数据XML
     *
     * @param beginDateStr : yyyymmdd-example-20190101
     * @param endDateStr   : example-20190131
     * @param methodName   : 接口名-考勤汇总(getAttendSum)、考勤明细(getAttendMsg)
     * @return : java.lang.StringBuilder
     * @author : YunTao.Li
     * @date : 2019/12/21 2019/12/21
     */
    private StringBuilder getAttendanceDetailResXML(String beginDateStr, String endDateStr, String methodName) throws Throwable {
        try {
            //第一步：创建服务地址，不是WSDL地址
            URL url = new URL(WSDL_ATTENDANCE);
            //第二步：打开一个通向服务地址的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //第三步：设置参数
            //3.1发送方式设置：POST必须大写
            connection.setRequestMethod("POST");
            //3.2设置数据格式：content-type
            connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
            //3.3设置输入输出，因为默认新创建的connection没有读写权限，
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //第四步：组织SOAP数据，发送请求
            String soapXML = getAttendanceRequestXML(beginDateStr, endDateStr, methodName);
            System.out.println("call attendance sync with soap xml :" + soapXML);
            OutputStream os = connection.getOutputStream();
            os.write(soapXML.getBytes());
            //第五步：接收服务端响应，打印
            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();
            String printStr = "code:" + responseCode + "msg:" + responseMessage;
            System.out.println(printStr);

            StringBuilder queryResXML = new StringBuilder();
            if (200 != responseCode) {
                //如果不成功则抛出异常
                throw new Throwable("同步服务器繁忙请重试，如再次重试失败请联系管理员");
            } else {
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);


                String temp = null;
                while (null != (temp = br.readLine())) {
                    temp = temp.replaceAll("&lt;", "<");
                    temp = temp.replaceAll("&gt;", ">");
                    temp = temp.replaceAll("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body><ns:getAttendMsgResponse xmlns:ns=\"http://com.swdp3.core.ws\"><ns:return>", "");
                    temp = temp.replaceAll("<\\?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"\\?>", "");
                    temp = temp.replaceAll("</ns:return></ns:getAttendMsgResponse></soapenv:Body></soapenv:Envelope>", "");
                    queryResXML.append(temp);
                }
                is.close();
                isr.close();
                br.close();
            }

            os.close();

            return queryResXML;
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 获得查询考勤接口的请求XML
     *
     * @param starttime  :
     * @param endtime    :
     * @param methodName : getAttendSum、getAttendMsg
     * @return : java.lang.String
     * @author : YunTao.Li
     * @date : 2019/12/21 2019/12/21
     */
    public static String getAttendanceRequestXML(String starttime, String endtime, String methodName) {
        String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body>"
                + "<" + methodName + " xmlns=\"http://com.swdp3.core.ws\">"
                + "<starttime>" + starttime + "</starttime>"
                + "<endtime>" + endtime + "</endtime>"
                + "</" + methodName + ">"
                + "</soap:Body>"
                + "</soap:Envelope>";
        return soapXML;
    }
}
